package swu.edu.cn.javaee.service;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import swu.edu.cn.javaee.entity.Group;
import swu.edu.cn.javaee.entity.GroupInfo;
import swu.edu.cn.javaee.mapper.GroupMapper;
import static swu.edu.cn.javaee.component.Signal.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class GroupService {
    @Resource
    private GroupMapper groupMapper;


    //创建群
    public String saveGroup(String gname){
        Group group=new Group();
        Date creation_time=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        group.setGname(gname);
        group.setCreation_time(format.format(creation_time));
        groupMapper.saveGroup(group);
        System.out.println(group);
        return SUCCESS_CODE;
    }

    //查看所有群
    public GroupInfo queryGroupList(){
        List<Group> groupList=groupMapper.queryGroupList();
        Integer count=groupMapper.count();
        GroupInfo groupInfo=new GroupInfo();
        if (groupList.size()!=0){
            groupInfo.setCode("0");
            groupInfo.setCount(String.valueOf(count));
            groupInfo.setMsg("");
            groupInfo.setData(groupList);
            return groupInfo;
        }
        return null;
    }

    //推荐群
    public String recommend(String gid){
        Group group=groupMapper.queryGroupById(gid);
        if (group!=null){
            group.setRecommend(group.getRecommend()+1);
            groupMapper.updateGroup(group);
            System.out.println(group);
            return SUCCESS_CODE;
        }
        else {
            return FAILED_CODE_NO_GROUP;
        }
    }

    //避雷群
    public String not_recommend(String gid){
        Group group=groupMapper.queryGroupById(gid);
        if (group!=null){
            group.setRecommend(group.getRecommend()-1);
            groupMapper.updateGroup(group);
            System.out.println(group);
            return SUCCESS_CODE;
        }
        else {
            return FAILED_CODE_NO_GROUP;
        }
    }
    //根据id查找群
    public Group queryGroupById(String gid){
        Group group=groupMapper.queryGroupById(gid);
        if (group!=null){
            return group;
        }
        else {
            return null;
        }
    }

    //解散群组
    public String deleteGroup(String gid){
        Group result=groupMapper.queryGroupById(gid);
        if (result!=null){
            groupMapper.deleteGroup(result);
            return SUCCESS_CODE;
        }
        else {
            return FAILED_CODE_NO_GROUP;
        }
    }

}
